import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_page/community_business/post_detail_page/post_detail_page.dart';
import 'package:tiktokadult/hj_page/community_business/widget/community_post_widget.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/refresh/pull_refresh.dart';

import '../../../../hj_model/user/mine_video.dart';
import '../../../../hj_model/video_model.dart';
import '../../../../hj_utils/api_service/common_service.dart';
import '../../../../tools_base/loading/l_error_widget.dart';
import '../../../../tools_base/loading/loading_alert_widget.dart';

///我发布的帖子
class UserPublishPostTabView extends StatefulWidget {
  final int selectStatus; // 0通过 1审核中 2 已拒绝, -1 全部
  final bool isEditStatus;
  final int? uid; // 用户id
  final Function(int)? countCallback;

  UserPublishPostTabView({
    this.selectStatus = 0,
    this.isEditStatus = false,
    this.uid,
    this.countCallback,
    super.key,
  });

  @override
  State<StatefulWidget> createState() {
    return UserPublishPostTabViewState();
  }
}

class UserPublishPostTabViewState extends State<UserPublishPostTabView> with TickerProviderStateMixin {
  RefreshController? refreshController;
  int currentPage = 1;
  List<VideoModel>? videoList;
  List<VideoModel> deleteList = [];

  List<String> get deleteIds {
    List<String> deleteArr = [];
    deleteList.forEach((element) {
      deleteArr.add(element.id ?? "");
    });
    return deleteArr;
  }

  int get selectStatus => widget.selectStatus;

  ///设置请求作品状态
  String? _getStatus() {
    if (selectStatus == 0) {
      // 通过
      return "1";
    } else if (selectStatus == 1) {
      //审核中
      return "0";
    } else if (selectStatus == 2) {
      // 已拒绝
      return "2";
    }
    return null;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _loadData();
    });
  }

  void _loadData({int page = 1, int size = 10}) async {
    try {
      MineCollect works = await MineService.fetchMyCollection(
        page: page,
        size: size,
        status: _getStatus(),
        uid: widget.uid,
      );
      currentPage = page;
      videoList ??= [];
      if (page == 1) {
        videoList?.clear();
        widget.countCallback?.call(works.total ?? 0);
      }
      videoList?.addAll((works.list ?? <VideoModel>[]) as List<VideoModel>);
      if ((works.list?.length ?? 0) < size) {
        refreshController?.loadNoData();
      } else {
        refreshController?.loadComplete();
      }
    } catch (e) {
      refreshController?.loadComplete();
      videoList ??= [];
    }
    refreshController?.refreshCompleted();
    setState(() {});
  }

  Future deleteEvent() async {
    if (deleteIds.isEmpty) return;
    LoadingAlertWidget.show();
    try {
      await CommonService.postDelArr(deleteIds);
    } catch (e) {
      debugLog(e);
    }
    LoadingAlertWidget.cancel();
    deleteList.clear();
  }

  void _skipToDetailEvent(VideoModel videoModel) {
    ///进入图文详情
    if (!widget.isEditStatus) {
      Get.toNamed(PostDetailPage.routeName, arguments: PostDetailPageArgument(id: videoModel.id, models: videoList));
    }
  }

  @override
  Widget build(BuildContext context) {
    if (videoList == null) {
      return LoadingCenterWidget();
    } else if (videoList!.isEmpty) {
      return CErrorWidget(
        retryOnTap: widget.isEditStatus
            ? null
            : () {
                videoList = null;
                setState(() {});
                _loadData();
              },
      );
    } else {
      return pullYsRefresh(
        onInit: (ctr) => refreshController = ctr,
        onRefresh: (ctr) => _loadData(),
        enablePullUp: videoList?.isNotEmpty == true,
        enablePullDown: widget.isEditStatus == false,
        onLoading: (ctr) {
          _loadData(page: currentPage + 1);
        },
        child: _buildListView(),
      );
    }
  }

  Widget _buildListView() {
    return ListView.builder(
      padding: EdgeInsets.zero,
      itemCount: videoList?.length ?? 0,
      itemBuilder: (BuildContext context, int index) {
        var model = videoList![index];
        return Container(
          padding: EdgeInsets.only(bottom: 12),
          child: Stack(
            children: [
              CommunityPostWidget(
                videoModel: model,
                videoModels: videoList,
                isMyPublish: true,
                clickCallback: () {
                  _skipToDetailEvent(model);
                },
              ),
              if (widget.isEditStatus)
                Positioned.fill(
                  child: Container(
                    alignment: Alignment.center,
                    child: InkWell(
                      onTap: () {
                        deleteList.add(model);
                        videoList?.remove(model);
                        setState(() {});
                      },
                      child: Image.asset("delete_icon.webp".mineImgPath, width: 50, height: 50),
                    ),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }
}
